#include "KmySceneManager.h"
#include "KmyRandom.h"

KmySceneManager::KmySceneManager()
{
    is_exit = false;
    cur_scene_type = 0;
    next_scene_type = 0;
    cur_scene = NULL;
    timer = NULL;
    interval = 17;
    screen_count = 0;
    screens = NULL;
}

KmySceneManager::~KmySceneManager(){
    if (cur_scene!=NULL){
        cur_scene->finalize();
        delete cur_scene;
    }
}

KmyIScene* KmySceneManager::getCurScene(){
    return cur_scene;
}

void KmySceneManager::run(){
//    if (timer!=NULL){
        timer->start();
        last_time = 0;
//    }
        is_exit = false;
    while(1){
        logic();
        render();

        if (is_exit){
//            if (timer!=NULL){
                timer->stop();
//            }
            return;
        }
//        if (timer!=NULL){
            int cur_time = timer->elapsed();
            while (cur_time-last_time<interval){
                cur_time = timer->elapsed();
            }
            last_time = cur_time;
//        }
    }
}

void KmySceneManager::logic()
{
    controller_pad->readKey();
    if (next_scene_type!=0){
        if (cur_scene!=NULL){
            cur_scene->finalize();
            delete cur_scene;
            cur_scene = NULL;
        }
        cur_scene_type = next_scene_type;
        next_scene_type = 0;
    }
    if (cur_scene!=NULL){
        cur_scene->logic();
    }else{
        if (cur_scene_type!=0){
            cur_scene = createScene(cur_scene_type);
            cur_scene->initialize();
            // 初始化随机数生成器
            KmyRandom::getInstance()->setSeed(timer->elapsed());
        }
    }
}

void KmySceneManager::render()
{
    if (cur_scene!=NULL){
        cur_scene->render();
    }
}

void KmySceneManager::changeScene(u8 scene_type){
    if (scene_type == cur_scene_type || scene_type == next_scene_type){
        return;
    }else{
        next_scene_type = scene_type;
    }
}

int KmySceneManager::getEnginePassTime(){
    return timer->elapsed();
}

KmyIControllerPad* KmySceneManager::getControllerPad(){
    return controller_pad;
}

ITimer* KmySceneManager::getTimer(){
    return timer;
}

void KmySceneManager::exit(){
    is_exit = true;
}
